package org.millioncall.yueyoga.admin.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Hall;
import org.millioncall.yueyoga.admin.model.HomePageLiftClub;
import org.millioncall.yueyoga.admin.model.HomePageTaskRecord;
import org.millioncall.yueyoga.admin.model.Task;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.model.UserHallModel;
import org.millioncall.yueyoga.admin.service.LiftClubService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.StatusService;
import org.millioncall.yueyoga.admin.service.TaskService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.millioncall.yueyoga.common.GlobalService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

//created by zangjy on 2012-3-23
@Controller
public class AdminAction extends BaseAction {
	private TaskService taskService;
	private UserService userService;
	private StatusService statusService;
	private MemberService memberService;
	private LiftClubService liftClubService;

	public LiftClubService getLiftClubService() {
		return liftClubService;
	}

	public void setLiftClubService(LiftClubService liftClubService) {
		this.liftClubService = liftClubService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public StatusService getStatusService() {
		return statusService;
	}

	public void setStatusService(StatusService statusService) {
		this.statusService = statusService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}
	
	@RequestMapping(value = "/testException.jhtml")
	public String testException(){
		int n = 10/0;
		return null;
	}

	/**
	 * 无权限页面跳转
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/accessdenid.jhtml")
	public String toAccessDenidPage(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String errorTitle = "错误";
		String errorMsg = "友情提示：您无操作此页面的权限，请联系管理员或使用更高权限极的账户登录";

		super.initFrontHeader(request, model);

		model.put("errorTitle", errorTitle);
		model.put("errorMsg", errorMsg);
		return "error";
	}

	/**
	 * 错误页面跳转
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/error.jhtml")
	public String toErrorPage(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String errorTitle = "错误";
		String errorMsg = "友情提示：数据错误或您的操作出现异常，请联系管理员或稍候重试";
		String errorException = "";

		Object requestErrorTitle = request
				.getParameter(GlobalConstants.ERROR_TITLE_KEY);
		Object requestErrorMsg = request
				.getParameter(GlobalConstants.ERROR_MSG_KEY);
		Object requestExceptionContent = request
				.getParameter(GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY);

		if (requestErrorTitle == null) {
			requestErrorTitle = request
					.getAttribute(GlobalConstants.ERROR_TITLE_KEY);
		}

		if (requestErrorMsg == null) {
			requestErrorMsg = request
					.getAttribute(GlobalConstants.ERROR_MSG_KEY);
		}

		if (requestExceptionContent == null) {
			requestExceptionContent = request
					.getAttribute(GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY);
		}

		if (requestErrorTitle != null
				&& StringUtils.isNoneBlank(requestErrorTitle.toString())) {
			errorTitle = requestErrorTitle.toString();
		}

		if (requestErrorMsg != null
				&& StringUtils.isNoneBlank(requestErrorMsg.toString())) {
			errorMsg = requestErrorMsg.toString();
		}

		if (requestExceptionContent instanceof Throwable) {
			errorException = GlobalService
					.buildStringOfException((Throwable) requestExceptionContent);
		} else {
			errorException = requestExceptionContent == null ? ""
					: requestExceptionContent.toString();
		}

		super.initFrontHeader(request, model);

		model.put("errorTitle", errorTitle);
		model.put("errorMsg", errorMsg);
		model.put("errorException", errorException);
		return "error";
	}

	@RequestMapping(value = "/main.jhtml")
	public String findTasksIndex(String name, String type,
			HttpServletRequest request, ModelMap model) {
		// 初始化头部
		initFrontHeader(request, model);
		HttpSession session = request.getSession();
		User user = this.getUser(request);
		// 过期的任务数量
		if (user == null) {
			return "redirect:toLogin.jhtml";
		}
		
		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}

		String ordercol = request.getParameter("ordercol");
		String order = request.getParameter("order");

		if (StringUtils.isBlank(order)) {
			order = "desc";
		}
		model.put("initOrder", order);

		if (StringUtils.isNoneBlank(ordercol)) {
			if ("dqsj".equals(ordercol)) {// 到期时间
				model.put("orderType", "t.expirydate " + order);
			} else if ("xxly".equals(ordercol)) {// 信息来源
				model.put("orderType", "m.marketingSource  " + order);
			} else if ("zt".equals(ordercol)) {// 状态
				model.put("orderType", "s2.name " + order);
			} else if ("zzt".equals(ordercol)) {// 子状态
				model.put("orderType", "s1.name " + order);
			}
			model.put("initOrderCol", ordercol);
		}
		String hallname = this.getUser(request).getOrganizationId();
		session.setAttribute("hal", userService.findUserByHallName(hallname));
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		
		model.put("groups", groupIds);
		String codeString = request.getParameter("hallcode");
		if(StringUtils.isNotBlank(codeString)){
			this.getUser(request).setOrganizationId(codeString);
		}
		Map<String, Object> map6 = new HashMap<String, Object>();
		map6.put("hallcode", this.getUser(request).getOrganizationId());
		model.put("hallcode", this.getUser(request).getOrganizationId());
		map6.put("userId", this.getUser(request).getId());
		session.setAttribute("userHall", userService.findUserGroupHall(map6));
		PaginatedList<HomePageTaskRecord> pl = taskService.findHomeTasksInPage(
				model, start, limit);
		String organizationId = user.getOrganizationId();
		// 查询近期的5个活动
		List<HomePageLiftClub> lcs = this.liftClubService.findLastLiftClubs(5,organizationId);
		model.put("lastLiftClubs", lcs);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		map.put("expiryDate",
				DateTimeUtils.getInstance()
						.format(new Date(), "yyyy-MM-dd"));
		model.put("pl", pl);
		model.put("count", pl == null ? 0 : pl.size());
		model.put(
				"expiryCount",
				taskService.findExpiredTaskCount(map));
		return "main";
	}

	public PaginatedList<Task> findTasksByConts(String name, String type,
			String aboutToExpiry, HttpServletRequest request,
			Map<String, Object> map) {
		int start = 0;
		int limit = 10;

		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}

		String subStatusId = request.getParameter("subStatusId");
		String memberId = request.getParameter("memberId");
		String TaskUserId = request.getParameter("userId");
		String resporId = request.getParameter("resporId");
		String memberStatus = request.getParameter("memberStatus");
		String expirydatestart = request.getParameter("expiryStart");
		String expirydatesend = request.getParameter("expiryEnd");
		String createStart = request.getParameter("createStart");
		String createEnd = request.getParameter("createEnd");
		String finishdatestart = request.getParameter("finishStart");
		String finishdateend = request.getParameter("finishEnd");
		String responsible = request.getParameter("responsible");
		String taskStatus = request.getParameter("taskStatus");
		String parentStatus = request.getParameter("parentStatus");
		// String orderType = request.getParameter("orderType");
		User user = this.getUser(request);
		
		if (StringUtils.isNotBlank(taskStatus)) {
			map.put("taskStatus", taskStatus);
		}
		if (StringUtils.isNotBlank(subStatusId)) {
			map.put("userid", user.getId());
		}
		if (StringUtils.isNotBlank(responsible)) {
			map.put("responsible", responsible);
		}
		if (StringUtils.isNotBlank(TaskUserId)) {
			map.put("TaskUserId", TaskUserId);
		}
		if (StringUtils.isNotBlank(subStatusId)) {
			map.put("subStatusId", subStatusId);
		}
		if (StringUtils.isNotBlank(memberId)) {
			map.put("memberId", memberId);
		}
		if (StringUtils.isNotBlank(resporId)) {
			map.put("resporId", resporId);
		}
		if (StringUtils.isNotBlank(parentStatus)) {
			map.put("parentStatus", parentStatus);
		}
		if (StringUtils.isNotBlank(memberStatus)) {
			map.put("memberStatus", memberStatus);
		}
		if (StringUtils.isNotBlank(createStart)) {
			map.put("createStart", createStart);
		}
		if (StringUtils.isNotBlank(createEnd)) {
			map.put("createEnd", createEnd);
		}
		if (StringUtils.isNotBlank(expirydatestart)) {
			map.put("expirydatestart", expirydatestart);
		}
		if (StringUtils.isNotBlank(expirydatesend)) {
			map.put("expirydatesend", expirydatesend);
		}
		if (StringUtils.isNotBlank(finishdatestart)) {
			map.put("finishdatestart", finishdatestart);
		}
		if (StringUtils.isNotBlank(finishdateend)) {
			map.put("finishdateend", finishdateend);
		}
		if (StringUtils.isNotBlank(name)) {
			map.put("taskName", name);
		}
		if (StringUtils.isNotBlank(type)) {
			map.put("taskType", type);
		}

		String ordercol = request.getParameter("ordercol");
		String order = request.getParameter("order");

		if (StringUtils.isBlank(order)) {
			order = "desc";
		}
		map.put("initOrder", order);

		if (StringUtils.isNoneBlank(ordercol)) {
			if ("dqsj".equals(ordercol)) {// 到期时间
				map.put("orderType", "t.expirydate " + order);
			} else if ("xxly".equals(ordercol)) {// 信息来源
				map.put("orderType", "m.marketingSource " + order);
			} else if ("zt".equals(ordercol)) {// 状态
				map.put("orderType", "s2.name " + order);
			} else if ("zzt".equals(ordercol)) {// 子状态
				map.put("orderType", "s1.name " + order);
			}
			map.put("initOrderCol", ordercol);
		}

		map.put("taskTypes", statusService.findByType(4));// 根据类型查询父类状态(工作安排)
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("key", "organizationId");
		map1.put("value", user.getOrganizationId());
		map1.put("hallcode", this.getUser(request).getOrganizationId());
		map.put("members", memberService.findMemberByProperty(map1));// 查询会员
		map.put("memberTypes", statusService.findByType(1));// 会员状态
		// 查询创建人
		List<User> creators = this.userService.findTaskUser();
		map.put("user", creators);
		// 查询负责人
		List<GroupUserModel> listUser = this.userService.findUsersByGroupId(
				"4", user.getOrganizationId());
		map.put("responsibles", listUser);
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Task> pl = taskService.findTasksInPage(map, start, limit);
		return pl;
	}	
	
}